package com.example.myapplication.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.R;
import com.example.myapplication.dao.MessageDao;
import com.example.myapplication.entity.Message;

public class AddMessageActivity extends AppCompatActivity {

    // View
    private TextView cancelBtn;
    private TextView saveBtn;
    private EditText usernameEdit;
    private EditText latestMsgEdit;
    private EditText timeEdit;

    private MessageDao messageDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_message);
        messageDao = new MessageDao(getBaseContext());
        bindView();

    }

    private void bindView() {
        cancelBtn = findViewById(R.id.tv_cancel_msg);
        saveBtn = findViewById(R.id.tv_save_msg);
        usernameEdit = findViewById(R.id.et_username);
        latestMsgEdit = findViewById(R.id.et_latest_message);
        timeEdit = findViewById(R.id.et_time);

        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = usernameEdit.getText().toString();
                String latestMsg = latestMsgEdit.getText().toString();
                String time = timeEdit.getText().toString();
                if (username == null || username.equals("")) {
                    Toast res = Toast.makeText(getBaseContext(), "请输入用户名", Toast.LENGTH_SHORT);
                    res.show();
                    return;
                }
                if (latestMsg == null || latestMsg.equals("")) {
                    Toast res = Toast.makeText(getBaseContext(), "请输入消息内容", Toast.LENGTH_SHORT);
                    res.show();
                    return;
                }
                if (time == null || time.equals("")) {
                    Toast res = Toast.makeText(getBaseContext(), "请输入时间", Toast.LENGTH_SHORT);
                    res.show();
                    return;
                }

                Message message = new Message();
                message.setUserName(username);
                message.setLatestMessage(latestMsg);
                message.setTime(time);
                message.setPortrait("portrait");
                messageDao.saveMessage(message);

                Toast res = Toast.makeText(getBaseContext(), "保存成功", Toast.LENGTH_SHORT);
                res.show();
                finish();
            }
        });

    }
}
